import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: {
          title: '系统首页',
          requiresAuth: true
        }
      },
      {
        path: 'student-management',
        name: 'StudentManagement',
        component: () => import('@/views/StudentManagement.vue'),
        meta: {
          title: '学生管理',
          requiresAuth: true,
          roles: ['ADMIN', 'TEACHER', 'STUDENT']
        }
      },
      {
        path: 'teacher-management',
        name: 'TeacherManagement',
        component: () => import('@/views/TeacherManagement.vue'),
        meta: {
          title: '教师管理',
          requiresAuth: true,
          roles: ['ADMIN', 'TEACHER']
        }
      },
      {
        path: 'course-management',
        name: 'CourseManagement',
        component: () => import('@/views/CourseManagement.vue'),
        meta: {
          title: '课程管理',
          requiresAuth: true,
          roles: ['ADMIN', 'TEACHER', 'STUDENT']
        }
      },
      {
        path: 'enrollment-management',
        name: 'EnrollmentManagement',
        component: () => import('@/views/EnrollmentManagement.vue'),
        meta: {
          title: '选课管理',
          requiresAuth: true,
          roles: ['ADMIN', 'STUDENT']
        }
      },
      {
        path: 'grade-management',
        name: 'GradeManagement',
        component: () => import('@/views/GradeManagement.vue'),
        meta: {
          title: '成绩管理',
          requiresAuth: true,
          roles: ['ADMIN', 'TEACHER', 'STUDENT']
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: {
          title: '个人资料',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: {
      title: '页面不存在'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫:', { to: to.path, from: from.path })
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 学生信息管理系统` : '学生信息管理系统'
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 直接使用state而不是getter，避免响应式问题
    const token = store.state.user.token
    console.log('需要认证，当前token (state):', token)
    if (!token) {
      console.log('没有token，重定向到登录页')
      next('/login')
      return
    }
    
    // 检查角色权限
    if (to.meta.roles) {
      // 直接使用state而不是getter，避免响应式问题
      const userRole = store.state.user.userInfo?.role || ''
      console.log('需要角色权限:', to.meta.roles, '当前角色:', userRole)
      console.log('当前用户信息:', store.state.user.userInfo)
      
      if (!userRole) {
        console.log('用户角色为空，尝试从token重新解析')
        // 如果用户角色为空，尝试从token重新解析
        const { parseToken } = await import('@/utils/auth')
        const tokenInfo = parseToken(token)
        if (tokenInfo) {
          const roleMapping = {
            '管理员': 'ADMIN',
            '教师': 'TEACHER', 
            '学生': 'STUDENT'
          }
          
          // 处理角色映射，支持中文和英文
          let parsedRole = tokenInfo.role
          if (roleMapping[tokenInfo.role]) {
            parsedRole = roleMapping[tokenInfo.role]
          } else if (['ADMIN', 'TEACHER', 'STUDENT'].includes(tokenInfo.role)) {
            parsedRole = tokenInfo.role // 已经是英文，直接使用
          }
          
          console.log('从token解析的角色:', parsedRole)
          
          if (to.meta.roles.includes(parsedRole)) {
            console.log('权限验证通过，允许访问')
            next()
            return
          }
        }
      }
      
      if (!to.meta.roles.includes(userRole)) {
        console.log('权限不足，重定向到dashboard')
        ElMessage.error('权限不足')
        next('/dashboard')
        return
      }
    }
  }
  
  // 已登录用户访问登录页面，重定向到仪表板
  if (to.path === '/login' && store.state.user.token) {
    console.log('已登录用户访问登录页，重定向到dashboard')
    next('/dashboard')
    return
  }
  
  console.log('路由守卫通过，允许访问:', to.path)
  next()
})

export default router
